/*
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * This file is part of Harmattan SmashMiner OpenGL game application.
 * 
 * Harmattan SmashMiner OpenGL Example Application version 1.0.0
 *  
 * Latest update: 15.4.2011
 *
 * The Harmattan SmashMiner OpenGL example application demonstrates how to use 
 * the OpenGL ES in Harmattan devices.
 *
 * This example is provided as a starting point for 3rd party
 * developers (you) to ease the implementation of OpenGL based 
 * games. Ideas, parts of code or methodologies that this
 * example application uses can be freely used without restrictions.
 *
 * See file README.txt how to build and compile this example application
 * in the Harmattan SDK environment. 
 * 
 * See file INSTALL.txt to find out what is required to run this
 * application and how to install the application to the device or
 * alternatively in QEMU-emulator.
 *
 * The LICENSE.txt file explains the license this software is provided
 * with. A copy of the same license is included in this source file.
 * 
 */

/*
 * Copyright (C) 2011 by Nokia Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "pulseaudiooutput.h"

#ifdef SMASHMINER_CONFIG_ENABLE_SOUND_ENGINE_PULSE_AUDIO

#include <QBuffer>
#include <QDebug>

#include "soundenginepulseaudio.h"

/*!
    \class PulseAudioOutput
    \brief Pulse Audio output device to play sound effects.

    Output device that plays sound effects using Pulse Audio sound server.
    Contains also data buffers for different sound effects.

    \sa SoundEnginePulseAudio SoundEngine
*/

//
// CALLBACKS FOR AUDIO OUTPUT
//
static void  outputStreamWriteCallback(pa_stream *stream, size_t length, void *userdata)
{
    Q_UNUSED(stream);
    Q_UNUSED(length);
    Q_UNUSED(userdata);
#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "outputStreamWriteCallback length " << length;
#endif
    SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();
    pa_threaded_mainloop_signal(soundEngine->mainloop(), 0);
}

static void outputStreamStateCallback(pa_stream *stream, void *userdata)
{
    Q_UNUSED(userdata)
    pa_stream_state_t state = pa_stream_get_state(stream);
#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "Stream state: " << state;
#endif
    switch (state) {
        case PA_STREAM_CREATING:
        case PA_STREAM_READY:
        case PA_STREAM_TERMINATED:
            break;

        case PA_STREAM_FAILED:
        default:
            qWarning() << QString("Stream error: %1").arg(pa_strerror(pa_context_errno(pa_stream_get_context(stream))));
            SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();
            pa_threaded_mainloop_signal(soundEngine->mainloop(), 0);
            break;
    }
}

static void outputStreamUnderflowCallback(pa_stream *stream, void *userdata)
{
    Q_UNUSED(stream)
    Q_UNUSED(userdata)
#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "Got a buffer underflow!";
#endif
}

static void outputStreamOverflowCallback(pa_stream *stream, void *userdata)
{
    Q_UNUSED(stream)
    Q_UNUSED(userdata)
#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "Got a buffer overflow!";
#endif
}

static void outputStreamLatencyCallback(pa_stream *stream, void *userdata)
{
    Q_UNUSED(stream)
    Q_UNUSED(userdata)

#ifdef DEBUG_PULSE_AUDIO
    const pa_timing_info *info = pa_stream_get_timing_info(stream);

    qDebug() << "Write index corrupt: " << info->write_index_corrupt;
    qDebug() << "Write index: " << info->write_index;
    qDebug() << "Read index corrupt: " << info->read_index_corrupt;
    qDebug() << "Read index: " << info->read_index;
    qDebug() << "Sink usec: " << info->sink_usec;
    qDebug() << "Configured sink usec: " << info->configured_sink_usec;
#endif
}

static void outputStreamSuccessCallback(pa_stream *stream, int success, void *userdata)
{
    Q_UNUSED(stream);
    Q_UNUSED(success);
    Q_UNUSED(userdata);

    SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();
    pa_threaded_mainloop_signal(soundEngine->mainloop(), 0);
}

static void outputStreamDrainComplete(pa_stream *stream, int success, void *userdata)
{
    Q_UNUSED(stream);
    Q_UNUSED(success);
    Q_UNUSED(userdata);

#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "Draining completed successfully: " << (bool)success;
#endif
}

//
// PulseAudioOutput implementation
//
/*!
    Constructs Pulse Audio output device.
*/
PulseAudioOutput::PulseAudioOutput(const QByteArray &device, QObject *parent)
    : QObject(parent)
    , device(device)
    , errorState(QAudio::NoError)
    , deviceState(QAudio::StoppedState)
    , opened(false)
    , bytesAvailable(0)
    , stream(0)
    , periodSizeValue(0)
    , tickTimer(new QTimer(this))
    , resuming(false)
    , effectPlaying(SoundNull)
    , volume(PA_VOLUME_NORM)
{
    connect(tickTimer, SIGNAL(timeout()), SLOT(feedSoundData()));
}

/*!
    Destructs Pulse Audio output device. Stops output.
*/
PulseAudioOutput::~PulseAudioOutput()
{
    stopOutput();
    disconnect(tickTimer, SIGNAL(timeout()));
    for (int i =0; i < NumberOfSounds; i++)
        delete soundsBufferArray[i];
}

/*!
    Sets \a volumelevel for output device.
*/
void PulseAudioOutput::setVolumeLevel(int volumeLevel)
{
    if (volumeLevel > 0)
        volume = (PA_VOLUME_NORM * volumeLevel)/10;
    else
        volume = PA_VOLUME_MUTED;
}

/*!
    Adds sound data for sound effect.
    Type of sound effect is given at the \a effectType parameter.
    Sound data is given at the \a soundBuffer parameter.
    \sa ::SoundEffectType.
*/
void PulseAudioOutput::addSoundBuffer(SoundEffectType effectType, QBuffer *soundBuffer)
{
    soundsBufferArray[effectType] = soundBuffer;
}

/*!
  Starts the playback of the sound affect given at the parameter \a soundEffect.
  \sa ::SoundEffectType.
*/
void PulseAudioOutput::start(SoundEffectType soundEffect)
{
    // First stop playing the previous effect
    stop();

    // Setup new effect
    effectPlaying = soundEffect;
    soundsBufferArray[effectPlaying]->open(QIODevice::ReadOnly);

    // set state to active
    deviceState = QAudio::ActiveState;

    // start new output
    startOutput();
}

/*!
  Stops the playback.
*/
void PulseAudioOutput::stop()
{
    if (deviceState == QAudio::StoppedState)
        return;

    errorState = QAudio::NoError;
    deviceState = QAudio::StoppedState;
    stopOutput();
}

/*!
  Resets the output device.
*/
void PulseAudioOutput::reset()
{
    stop();
}

/*!
  Set the output device to suspended state.
*/
void PulseAudioOutput::suspend()
{
    if (deviceState == QAudio::ActiveState || deviceState == QAudio::IdleState) {
        tickTimer->stop();
        deviceState = QAudio::SuspendedState;
        errorState = QAudio::NoError;

        SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();
        pa_operation *operation;

        pa_threaded_mainloop_lock(soundEngine->mainloop());

        operation = pa_stream_cork(stream, 1, outputStreamSuccessCallback, NULL);

        while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING)
            pa_threaded_mainloop_wait(soundEngine->mainloop());

        pa_operation_unref(operation);

        pa_threaded_mainloop_unlock(soundEngine->mainloop());
    }
}

/*!
  Resumes the output device from suspended state.
*/
void PulseAudioOutput::resume()
{
    if (deviceState == QAudio::SuspendedState) {
        resuming = true;

        SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();

        pa_threaded_mainloop_lock(soundEngine->mainloop());

        pa_operation *operation = pa_stream_cork(stream, 0, outputStreamSuccessCallback, NULL);

        while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING)
            pa_threaded_mainloop_wait(soundEngine->mainloop());

        pa_operation_unref(operation);

        operation = pa_stream_trigger(stream, outputStreamSuccessCallback, NULL);

        while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING)
            pa_threaded_mainloop_wait(soundEngine->mainloop());

        pa_operation_unref(operation);

        pa_threaded_mainloop_unlock(soundEngine->mainloop());

        deviceState = QAudio::ActiveState;

        errorState = QAudio::NoError;
        tickTimer->start(PeriodTimeMs);
    }
}

/*!
  Gets number of free bytes available at the output stream.
*/
int PulseAudioOutput::bytesFree() const
{
    if (deviceState != QAudio::ActiveState && deviceState != QAudio::IdleState)
        return 0;

    return pa_stream_writable_size(stream);
}

/*!
  Get error status from the output device.
*/
QAudio::Error PulseAudioOutput::error() const
{
    return errorState;
}

/*!
  Get status from the output device.
*/
QAudio::State PulseAudioOutput::state() const
{
    return deviceState;
}

/*!
  Sets the audio format used at playback. Format is given at the parameter \a format.
*/
void PulseAudioOutput::setFormat(const QAudioFormat &format)
{
    audioFormat = format;
}

/*!
  Gets the audio format used at playback.
*/
QAudioFormat PulseAudioOutput::format() const
{
    return audioFormat;
}

bool PulseAudioOutput::startOutput()
{
#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "open()";
#endif
    if (opened)
        return false;

    SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();
    pa_sample_spec spec = soundEngine->audioFormatToSampleSpec(audioFormat);

    if (!pa_sample_spec_valid(&spec)) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        qWarning() << "Pulse Audio pa_sample_spec not valid.";
        return false;
    }

    if (streamName.isNull())
        streamName = QString(QLatin1String("SmashMinerStream-%1-%2")).arg(::getpid()).arg(quintptr(this)).toUtf8();

#ifdef DEBUG_PULSE_AUDIO
        qDebug() << "Format: " << SoundEnginePulseAudio::instance()->sampleFormatToQString(spec.format);
        qDebug() << "Rate: " << spec.rate;
        qDebug() << "Channels: " << spec.channels;
        qDebug() << "Frame size: " << pa_frame_size(&spec);
#endif

    pa_threaded_mainloop_lock(soundEngine->mainloop());
    stream = pa_stream_new(soundEngine->context(), streamName.constData(), &spec, NULL);

#ifdef DEBUG_PULSE_AUDIO
    if (stream)
        qDebug() << "We have new stream!";
    else
        qDebug() << "No new stream!";
#endif

    pa_stream_set_state_callback(stream, outputStreamStateCallback, this);
    pa_stream_set_write_callback(stream, outputStreamWriteCallback, this);

    pa_stream_set_underflow_callback(stream, outputStreamUnderflowCallback, this);
    pa_stream_set_overflow_callback(stream, outputStreamOverflowCallback, this);
    pa_stream_set_latency_update_callback(stream, outputStreamLatencyCallback, this);

    pa_cvolume cvolume;
    pa_cvolume_set(&cvolume, spec.channels, volume);

    if (pa_stream_connect_playback(stream, device.data(), NULL, (pa_stream_flags_t)0, &cvolume, NULL) < 0) {
        qWarning() << "pa_stream_connect_playback() failed!";
        return false;
    }

    while (pa_stream_get_state(stream) != PA_STREAM_READY)
        pa_threaded_mainloop_wait(soundEngine->mainloop());
    pa_threaded_mainloop_unlock(soundEngine->mainloop());

#ifdef DEBUG_PULSE_AUDIO
    const pa_buffer_attr *buffer = pa_stream_get_buffer_attr(stream);

    qDebug() << "Buffering info:";
    qDebug() << "\tMax length: " << buffer->maxlength;
    qDebug() << "\tTarget length: " << buffer->tlength;
    qDebug() << "\tPre-buffering: " << buffer->prebuf;
    qDebug() << "\tMinimum request: " << buffer->minreq;
    qDebug() << "\tFragment size: " << buffer->fragsize;
#endif

    periodSizeValue = pa_usec_to_bytes(PeriodTimeMs*1000, &spec);

#ifdef DEBUG_PULSE_AUDIO
    qDebug() << "periodSizeValue = " << periodSizeValue;
#endif

    opened = true;
    tickTimer->start(PeriodTimeMs);

    return true;
}

/*!
 Feeds sound data to output device. Feed interval is
*/
void PulseAudioOutput::feedSoundData()
{
    if (deviceState == QAudio::StoppedState || deviceState == QAudio::SuspendedState)
        return;

    if (deviceState ==  QAudio::IdleState)
        bytesAvailable = bytesFree();

    writeDataToOutputDevice();
}

/*!
  Stops audio output.
*/
void PulseAudioOutput::stopOutput()
{
    tickTimer->stop();

    if (effectPlaying != SoundNull)
        soundsBufferArray[effectPlaying]->close();

    effectPlaying = SoundNull;

    if (stream) {
        SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();
        pa_threaded_mainloop_lock(soundEngine->mainloop());
        pa_operation *o;

        pa_stream_set_write_callback(stream, NULL, NULL);

        if (!(o = pa_stream_drain(stream, outputStreamDrainComplete, NULL))) {
            qWarning() << QString("pa_stream_drain(): %1").arg(pa_strerror(pa_context_errno(pa_stream_get_context(stream))));
            return;
        }
        pa_operation_unref(o);

        pa_stream_disconnect(stream);
        pa_stream_unref(stream);
        stream = NULL;

        pa_threaded_mainloop_unlock(soundEngine->mainloop());
    }
    opened = false;
}

/*!
  Writes sound data from sound buffer to output device.
*/
qint64 PulseAudioOutput::writeDataToOutputDevice()
{
    resuming = false;
    qint64 bytesWritten = 0;
    int length = 0;
    int chunks = bytesAvailable/periodSizeValue;

#ifdef DEBUG_PULSE_AUDIO

    qDebug() << "chunks = " << chunks;

#endif

    if (chunks==0) {
        bytesAvailable = bytesFree();
        return bytesWritten;
    }

    char buffer[periodSizeValue];

    length = soundsBufferArray[effectPlaying]->read(buffer, periodSizeValue);

#ifdef DEBUG_PULSE_AUDIO

    qDebug() << "audioSource->read() lenght = " << length;

#endif

    if (length > 0) {
        if (deviceState != QAudio::ActiveState) {

#ifdef DEBUG_PULSE_AUDIO

            qDebug() << "if (deviceState != QAudio::ActiveState)";
#endif

            return bytesWritten;
        }

        bytesWritten = write(buffer, length);

#ifdef DEBUG_PULSE_AUDIO

        qDebug() << "write() bytesWritten = " << bytesWritten;
#endif

    } else {

#ifdef DEBUG_PULSE_AUDIO

        qDebug() << "Nothing to be read from device = " << bytesWritten;
        qDebug() << "stopOutput()";

#endif

        // Stop playing the effect
        stop();
    }

    return bytesWritten;
}

/*!
  Writes \a data with \a length to the Pulse Audio stream.
*/
qint64 PulseAudioOutput::write(const char *data, qint64 length)
{
    SoundEnginePulseAudio *soundEngine = SoundEnginePulseAudio::instance();

    pa_threaded_mainloop_lock(soundEngine->mainloop());
    pa_stream_write(stream, data, length, 0, 0, PA_SEEK_RELATIVE);
    pa_threaded_mainloop_unlock(soundEngine->mainloop());

    errorState = QAudio::NoError;

    if (deviceState != QAudio::ActiveState)
        deviceState = QAudio::ActiveState;

    return length;
}

#endif
